Serving Static Files back to Client

After I Upload Files with next-connect and Multer I wanted to serve those same files back to the client. Ahh but not so fast says NextJS.

!note
Only assets that are in the public directory at link will be served by Next.js. Files added at runtime won't be available. We recommend using a third party service like AWS S3 for persistent file storage.

create an api endpoint

./pages/api/images-endpoint/[...slug].js

import fs from "fs";
import path from "path";

export default function handler(req, res) {
  const imagePath = req.query.slug.join("/");
  const filePath = path.resolve(".", `./public/uploads/${imagePath}`);
  const imageBuffer = fs.readFileSync(filePath);
  res.setHeader("Content-Type", "image/jpg");
  return res.send(imageBuffer);
}

Seperate Nginx server

Try and use nginx or another webserver to serve the public directory. That way it will serve newly added files without having to write extra code to serve files in nextjs. link

server {
  /images/ {
    root /var/www/site/public
  }
}

Express server inside NextJS

https://stackoverflow.com/a/70490960/15579591

other stuff

Looks like we could fiddle with a custom server but that looks like a bigger headache Advanced Features: Custom Server | Next.js (nextjs.org)


Credits